<!--产品标准产能：productStandardCapacity-->
<template>
  <basic-container>
    <el-row>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :search.sync="query"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <!-- <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.productStandardCapacity_add" @click="handleAdd">新 增</el-button> -->
          <!-- <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productStandardCapacity_delete" @click="handleDelete">删 除</el-button> -->
          <el-button type="warning" size="small" icon="el-icon-upload2" v-if="permission.productStandardCapacity_add" @click="handleImport">导 入</el-button>
          <el-button type="warning" size="small" v-if="permission.productStandardCapacity_ruleConfig" @click="ruleConfig">规则配置</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            v-if="permission.productStandardCapacity_view && !scope.row.parentId"
            @click="handleDetail(scope.row, scope.index)"
          >
            详情
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            v-if="permission.productStandardCapacity_edit && !scope.row.parentId"
            @click="handleEdit(scope.row, scope.index)"
          >
            编辑
          </el-button>
          <!-- <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            v-if="permission.productStandardCapacity_delete && !scope.row.parentId"
            @click="handleRowDel(scope.row, scope.index)"
          >
            删除
          </el-button> -->
        </template>
      </avue-crud>
    </el-row>

    <!-- 编辑 -->
    <productStandardCapacityEdit ref="productStandardCapacityEdit" :showEditDialog="showEditDialog" @closeEditDialog="closeEditDialog"></productStandardCapacityEdit>
    <!-- 详情 -->
    <productStandardCapacityDetail ref="productStandardCapacityDetail" :showDetailDialog="showDetailDialog" @closeDetailDialog="closeDetailDialog">
    </productStandardCapacityDetail>
    <!-- 导入 -->
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.importUrl"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
    <el-dialog append-to-body title="规则配置" :visible.sync="showDialog" @close="closeDialog" width="30%">
      <p>不纳入计算范围：</p>
      <avue-form ref="ruleConfigForm" v-model="ruleConfigForm" v-if="showDialog" :option="ruleConfigOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="saveRuleConfig"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import productStandardCapacityEdit from '@/views/product/components/productStandardCapacityEdit.vue';
import productStandardCapacityDetail from '@/views/product/components/productStandardCapacityDetail.vue';
import importDialogComp from '@/components/dialog/import/index.vue';
import {
  getList,
  getDetail,
  add,
  update,
  capacityRemove,
  getAllSectionList,
  verifyMachineCodeOrPartNo,
  getUphRuleInfo,
  uphRuleSet
} from '@/api/product/productStandardCapacity';
import { mapGetters } from 'vuex';
export default {
  name: 'ProductStandardCapacity',
  components: {
    GlobalModalTemplate,
    productStandardCapacityEdit,
    productStandardCapacityDetail,
    importDialogComp
  },
  data() {
    return {
      sectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        rowKey: 'id',
        rowParentKey: 'parentId',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        searchSpan: 5,
        searchMenuSpan: 3,
        searchLabelWidth: 90,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        labelWidth: 100,
        menuWidth: 150,
        selection: false,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        selectable: (row, index) => {
          return !row.parentId;
        },
        column: [
          {
            label: '产品编码', //，可以多个，‘，’分隔，供详情选择产品时过滤使用
            prop: 'productPartNo',
            searchOrder: 1,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入产品编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            search: true,
            searchOrder: 4
          },
          {
            label: '产品类型',
            prop: 'productPartType',
            searchOrder: 2,
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '维护状态',
            prop: 'status',
            type: 'select',
            searchOrder: 3,
            dataType: 'number',
            search: true,
            dicData: [
              {
                label: '已维护',
                value: '2'
              },
              {
                label: '待维护',
                value: '1'
              }
            ]
          },
          {
            label: '更新人',
            prop: 'createUserName'
          },
          {
            label: '更新时间',
            prop: 'createTime'
          }
        ]
      },
      form: {},
      showEditDialog: false,
      showDetailDialog: false,
      query: {},
      cloneForm: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      visibile: false,
      importConfig: {
        show: false,
        importUrl: '/api/mes-product/standard-capacity/import',
        exportName: '产品标准产能导入模版.xlsx',
        title: '产品标准产能导入'
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      showDialog: false,
      ruleConfigForm: {},
      ruleConfigOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        column: [
          {
            label: '产量小于',
            prop: 'ruleValue',
            span: 24,
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value != '' && value != null) {
                    if (value <= 0) {
                      callback(new Error('产量不能小于等于0'));
                    } else {
                      callback();
                    }
                  } else {
                    callback();
                  }
                }
              }
            ]
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    // 获取工段级联列表
    this.getWorkSection();
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.productStandardCapacity_add, false),
        viewBtn: this.vaildData(this.permission.productStandardCapacity_view, false),
        delBtn: this.vaildData(this.permission.productStandardCapacity_delete, false),
        editBtn: this.vaildData(this.permission.productStandardCapacity_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    // 获取工段级联列表
    getWorkSection() {
      getAllSectionList()
        .then((res) => {
          let data = res.data.data;
          this.sectionList = data.map((item) => {
            return {
              label: item.name,
              value: item.id,
              code: item.code,
              lineList: item.lineList || []
            };
          });
        })
        .catch((err) => {});
    },
    rowSave(row, done, loading) {
      row['partNames'] = this.form.partNames;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      verifyMachineCodeOrPartNo({
        tableId: row.id,
        originMachineCode: this.cloneForm.machineCode,
        newMachineCode: row.machineCode,
        originPartNos: this.cloneForm.partNos,
        newPartNos: row.partNos
      }).then((res) => {
        if (res.data.code === 200) {
          update(row).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
            },
            (error) => {
              loading();
              console.log(error);
            }
          );
        }
      });
      done();
    },
    handleRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return capacityRemove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleImport() {
      this.importConfig.show = true;
    },
    handleDetail(row, index) {
      this.showDetailDialog = true;
      this.$refs.productStandardCapacityDetail.getData(row);
    },
    handleAdd() {
      this.showEditDialog = true;
      this.$refs.productStandardCapacityEdit.editDialog.title = '新增';
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartNo = '';
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartName = '';
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartModel = '';
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartType = '';
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartId = '';
      this.$refs.productStandardCapacityEdit.editDialog.tableData = [];
      this.$refs.productStandardCapacityEdit.getWorkSection(this.sectionList);
    },
    handleEdit(row, index) {
      this.showEditDialog = true;
      this.$refs.productStandardCapacityEdit.editDialog.title = '编辑';
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartNo = row.productPartNo;
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartName = row.productPartName;
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartModel = row.productPartModel;
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartType = row.productPartType;
      this.$refs.productStandardCapacityEdit.editDialog.form.productPartId = row.productPartId;
      this.$refs.productStandardCapacityEdit.getWorkSection(this.sectionList);
      if (row.id) {
        getDetail(row.id).then((res) => {
          let data = res.data.data;
          this.$refs.productStandardCapacityEdit.editDialog.tableData = structuredClone(data.standardCapacityDetailList);
          this.$refs.productStandardCapacityEdit.rowId = data.id;
        });
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('是否确认删除勾选产品的全部产能信息？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return capacityRemove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          this.cloneForm = this._cloneDeep(res.data.data);
        });
      }
      done();
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      // params.descs = 'create_time';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    codeClose(value) {
      if (value) {
        this.onLoad(this.page);
      }
    },
    closeEditDialog() {
      this.showEditDialog = false;
      this.onLoad(this.page, this.query);
    },
    closeDetailDialog() {
      this.showDetailDialog = false;
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    ruleConfig() {
      this.showDialog = true;
      getUphRuleInfo().then((res) => {
        this.ruleConfigForm.ruleValue = this._get(res, 'data.data', {});
      });
    },
    saveRuleConfig() {
      this.$refs.ruleConfigForm.validate(async (valid, done) => {
        if (valid) {
          uphRuleSet({ ruleValue: this.ruleConfigForm.ruleValue }).then((res) => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.showDialog = false;
          });
        }
        done();
      });
    },
    closeDialog() {
      this.ruleConfigForm = {};
    }
  }
};
</script>

<style lang="scss" scoped></style>
